<template>
  <div class="container">
    <a-card class="general-card" title="查询表格">
      <!--搜索-->
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="id" label="id">
                  <a-input v-model="formModel.id" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="title" label="标题">
                  <a-input v-model="formModel.title" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="content" label="内容">
                  <a-input v-model="formModel.content" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="userId" label="用户ID">
                  <a-input v-model="formModel.userId" placeholder="请输入" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <!--新建-->
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space></a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-plus />
            </template>
            新建
          </a-button>
          <a-tooltip content="刷新">
            <div class="action-icon" @click="search">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip content="密度">
              <div class="action-icon">
                <icon-line-height size="18" />
              </div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
        </a-col>
      </a-row>
      <!--表格-->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="cloneColumns as TableColumnData[]"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #avatar="{ record }">
          <a-space>
            <a-avatar :href="record.avatar">
              <img v-if="record.avatar" alt="avatar" :src="record.avatar" />
              <IconUser v-else />
            </a-avatar>
          </a-space>
        </template>
        <template #createTime="{ record }">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template #updateTime="{ record }">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template #operations="{ record }">
          <a-button type="text" size="small" @click="handleUpdate(record)">
            修改
          </a-button>
          <a-popconfirm content="你确定要删除?" @ok="handleDelete(record)">
            <a-button type="text" size="small" status="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <!--创建悬浮窗-->
    <CreateModal ref="createModal" @ok="reset" />
    <!--更新悬浮窗-->
    <UpdateModal ref="updateModal" @ok="reset" />
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import useLoading from '@/hooks/useLoading.ts';
import { Pagination } from '@/types/global.ts';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import cloneDeep from 'lodash/cloneDeep';
import CreateModal from './components/CreateModal.vue';
import UpdateModal from './components/UpdateModal.vue';
import { Message } from '@arco-design/web-vue';
import dayjs from 'dayjs';
import {
  deleteAnnouncementUsingPost,
  listAnnouncementVoByPageUsingPost
} from '@/service/backend/announcementController.ts';

type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };
const createModal = ref<InstanceType<typeof CreateModal>>();
const updateModal = ref<InstanceType<typeof UpdateModal>>();
const { loading, setLoading } = useLoading(true);
const renderData = ref<API.AnnouncementVO[]>([]);
const formModel = ref({});
const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);
const size = ref<SizeProps>('medium');
const basePagination: Pagination = {
  current: 1,
  pageSize: 5
};
const pagination = reactive({
  ...basePagination
});

const columns = computed<TableColumnData[]>(() => [
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '标题',
    dataIndex: 'title'
  },
  {
    title: '内容',
    dataIndex: 'content'
  },
  {
    title: '创建人',
    dataIndex: 'user.username'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    slotName: 'createTime'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    slotName: 'updateTime'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations'
  }
]);

const densityList = computed(() => [
  {
    name: '偏小',
    value: 'small'
  },
  {
    name: '中等',
    value: 'medium'
  },
  {
    name: '偏大',
    value: 'large'
  }
]);

onMounted(async () => {
  await fetchData();
});

/**
 * 处理添加
 */
const handleAdd = () => {
  createModal.value.open();
};

/**
 * 处理更新
 * @param row 当前行
 */
const handleUpdate = (row: API.AnnouncementVO) => {
  updateModal.value.open(cloneDeep(row));
};

/**
 * 处理删除
 * @param row 当前行
 */
const handleDelete = async (row: API.AnnouncementVO) => {
  try {
    const res = await deleteAnnouncementUsingPost({
      id: row.id
    });
    if (res.data && res.code === 0) {
      await reset();
      Message.success('删除成功');
    }
  } catch (e) {
    Message.error(`删除失败,${e.message}`);
  }
};

/**
 * 获取数据
 * @param params
 */
const fetchData = async (params: Pagination = { current: 1, pageSize: 20 }) => {
  setLoading(true);
  try {
    const { data, code } = await listAnnouncementVoByPageUsingPost(params);
    if (code === 0 && data) {
      renderData.value = data.records;
      pagination.current = Number(data.current);
      pagination.total = Number(data.total);
    }
  } catch (err) {
    Message.error(err.message);
  } finally {
    setLoading(false);
  }
};

/**
 * 搜索
 */
const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value
  });
};

/**
 * 监听页面发生变化
 * @param current 当前页面
 */
const onPageChange = (current: number) => {
  fetchData({ ...basePagination, current });
};

/**
 * 重置表格
 */
const reset = async () => {
  formModel.value = {};
  await fetchData();
};

/**
 * 列密度
 * @param val
 * @param _e
 */
const handleSelectDensity = (
  val: string | number | Record<string, any> | undefined,
  _e: Event
) => {
  size.value = val as SizeProps;
};

/**
 * 监听list的变化
 */
watch(
  () => columns.value,
  val => {
    cloneColumns.value = cloneDeep(val);
    cloneColumns.value.forEach((item, _index) => {
      item.checked = true;
    });
    showColumns.value = cloneDeep(cloneColumns.value);
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.action-icon {
  margin-left: 12px;
  cursor: pointer;
}

.active {
  color: #0960bd;
  background-color: #e3f4fc;
}

.setting {
  display: flex;
  align-items: center;
  width: 200px;

  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
